﻿using Microsoft.Extensions.Logging;
using Simple.Framework.Ioc;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 Simple.BasicNet.Core.Net
 * 接口名称 SocketManager
 * 开发人员：11920
 * 创建时间：2023/4/6 15:35:10
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace SimpleNet
{
	public class ClientManager: IClientManager
	{
	    private	ConcurrentDictionary<long,IConnection> clientsDic;
		private IContainer container;
		//private Stopwatch stopwatch;
		//private long time;
		private ILogger<ClientManager> logger;
		public ClientManager(IContainer container)
		{
			clientsDic=new ConcurrentDictionary<long, IConnection>();
			this.container = container;
			//stopwatch = new Stopwatch();
			logger=this.container.GetService<ILogger<ClientManager>>();	
		}

		public Tuple<bool,IConnection> AddClient(Socket client)
		{
		//	stopwatch.Start();
			var connection=container.GetService<IConnection>();
				connection.SetSocket(client);
			var data= Tuple.Create(clientsDic.TryAdd(connection.ConnectionID, connection), connection);
			//stopwatch.Stop();
			//time += stopwatch.ElapsedMilliseconds;
			//logger.LogInformation($"创建connection花费时间:{time}!");
			return data;
		}

		

		public  void RemoveClient(long ClientID)
		{
			if (clientsDic.ContainsKey(ClientID))
			{
				clientsDic.TryRemove(ClientID,out IConnection client);
				client.Dispose();
			}
		}

		public IEnumerable<IConnection> GetClients()
		{
			return clientsDic.Values;
		}

		public IConnection GetClient(long key)
		{
			if (clientsDic.ContainsKey(key))
			{
				return clientsDic[key];
			}
			return null;
		}
		public IEnumerable<IConnection> GetClient(long[] keys)
		{
			List<IConnection> clients = new List<IConnection>();
			foreach (var key in keys)
			{
				var client=GetClient(key);
				if (client!=null)
				{
					clients.Add(client);
				}
			}
			return clients;
		}

		public int GetClientCount()
		{
			return clientsDic.Count();
		}

		public bool ContainsKey(long key)
		{
			return clientsDic.ContainsKey(key);
			
		}
	}
}
